#include <hexstr.h>

int cvtHex2str(const char *hexptr, int hexsize, char *outstr, int outsize)
{
    static const char *hexCvtStr = "0123456789ABCDEF";
    uint8_t tmpid;
    if(!(hexptr && outstr && hexsize > 0 && outsize > 0))
    {
        logerror("data error");
        return 0;
    }
    if(outsize / 2 < hexsize)
    {
        // logwarn("%d < %d", outsize, hexsize * 2);
        hexsize = outsize / 2;
    }
    for (int i = 0; i < hexsize; i++)
    {
        tmpid = hexptr[i];
        outstr[i * 2] = hexCvtStr[(tmpid >> 4) & 0xf];
        outstr[i * 2 + 1] = hexCvtStr[(tmpid >> 0) & 0xf];
    }
    if(hexsize * 2 < outsize)
    {
        outstr[hexsize * 2] = 0;
    }
    return hexsize * 2;
}
// void logHexBuf(char *hexptr, int hexsize, const char *logFile, int logLine)
// {
// #if DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_LINUX
//     DEV_C51_XDATA_FLAG char tmpstr[1025];
// #elif DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_ARM32_MCU
//     DEV_C51_XDATA_FLAG char tmpstr[129];
// #elif DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_C51_MCU
//     DEV_C51_XDATA_FLAG char tmpstr[33];
// #endif
//     const char *tmpFileName;
//     (tmpFileName = strrchr(logFile, '/')) ? tmpFileName++ : (tmpFileName = logFile);
//     cvtHex2str(hexptr, hexsize, tmpstr, sizeof(tmpstr));
//     logdebug("%s,%d,hstr=%s", tmpFileName, logLine, tmpstr);
// }
int cvtStr2hex(const char *instr, int insize, char *hexptr, int hexsize)
{
    char tmphexstr[3] = {0};
    if(!(hexptr && insize && hexsize > 0 && insize > 0))
    {
        logerror("data error");
        return 0;
    }
    if(hexsize * 2 < insize)
    {
        // logwarn("%d * 2 < %d", hexsize, insize);
        insize = hexsize * 2;
    }
    hexsize = insize / 2;
    for (int i = 0; i < hexsize; i++)
    {
        tmphexstr[0] = instr[i * 2];
        tmphexstr[1] = instr[i * 2 + 1];
        hexptr[i] = strtol(tmphexstr, NULL, 16);
    }
    return hexsize;
}

void logHexBufStr(const char *expStr, const char *hexptr, int hexsize)
{
#if DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_LINUX
    DEV_C51_XDATA_FLAG char tmpHexStr[1025];
#elif DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_ARM32_MCU
    DEV_C51_XDATA_FLAG char tmpHexStr[129];
#elif DEVICE_PLATFORM_CONFIGURE == DEVICE_PLATFORM_C51_MCU
    DEV_C51_XDATA_FLAG char tmpHexStr[65];
#endif
    cvtHex2str(hexptr, hexsize, tmpHexStr, sizeof(tmpHexStr));
    logdebug("%s:%s", expStr, tmpHexStr);
}
